﻿import datetime
import os
import ftplib
from sqlite import query_ignore_list, add_to_sync_history
class ftp_connect:
    server_address = '120.46.196.67'  # FTP服务器地址
    username = 'ftptest12'
    password = '123456789'
    local_path = r'E:\FTP'  # 本地文件夹路径
    remote_path = '/home/ftproot/ftptest/fjn'  # FTP服务器文件夹路径

    @classmethod
    def connect(cls):
        ftp = ftplib.FTP(cls.server_address)
        try:
            ftp.login(cls.username, cls.password)
        except Exception as e:
            print(e)
            return None
        return ftp

    @classmethod
    def close(cls, ftp):
        ftp.quit()

    @classmethod
    def upload(cls, ftp):
        try:
            for root, dirs, files in os.walk(cls.local_path):
                for dir_name in dirs:
                    local_dir = os.path.join(root, dir_name)
                    remote_dir = os.path.join(cls.remote_path, os.path.relpath(local_dir, cls.local_path))
                    amended_remote_dir = remote_dir.replace("\\", "/")
                    try:
                        ftp.mkd(amended_remote_dir)
                        print("创建目录 %s 成功" % amended_remote_dir)
                    except ftplib.error_perm as e:
                        if not str(e).startswith('550'):
                            raise

            for root, dirs, files in os.walk(cls.local_path):
                for file_name in files:
                    local_file = os.path.join(root, file_name)
                    remote_file = os.path.join(cls.remote_path, os.path.relpath(local_file, cls.local_path))
                    amended_remote_file = remote_file.replace("\\", "/")
                    with open(local_file, 'rb') as f:
                        ftp.storbinary('STOR %s' % amended_remote_file, f)
                        print('上传文件 %s 到 %s 成功' % (local_file, amended_remote_file))
        except ftplib.all_errors as e:
            print("失败")

    @classmethod
    def local_sync(cls, ftp, temp_remote_path, temp_local_path, ftp_size, local_size, file_name):
        print(temp_local_path, '本地路径')
        print(temp_remote_path, '远程路径')
        print(file_name, '文件名')
        res = query_ignore_list(file_name, temp_remote_path, temp_local_path)
        if res == []:
            add_to_sync_history(temp_remote_path + '/' + file_name, '本地为主', datetime.datetime.now())
            if ftp_size != local_size:
                if ftp_size != -2:
                    cls.ftp_delete(ftp, temp_remote_path, file_name)
                if local_size != -1:
                    with open(temp_local_path + '\\' + file_name, 'rb') as f:
                        ftp.storbinary('STOR %s' % temp_remote_path + '/' + file_name, f)
                        print('上传文件 %s 到 %s 成功' % (
                        temp_local_path + '\\' + file_name, temp_remote_path + '/' + file_name))
        else:
            print('忽略列表中的文件不同步')

    @classmethod
    def ftp_sync(cls, ftp, temp_remote_path, temp_local_path, ftp_size, local_size, file_name):
        print(temp_local_path, '本地路径_ftp')
        print(temp_remote_path, '远程路径')
        print(file_name, '文件名')
        res = query_ignore_list(file_name, temp_remote_path, temp_local_path)
        if res == []:
            add_to_sync_history(temp_remote_path + '/' + file_name, '服务器为主', datetime.datetime.now())
            if local_size != ftp_size:
                if local_size != -1:
                    try:
                        os.remove(temp_local_path + '\\' + file_name)
                    except Exception as e:
                        print('删除失败', e)
                if ftp_size != -2:
                    with open(temp_local_path + '\\' + file_name, 'wb') as f:
                        ftp.retrbinary('RETR ' + temp_remote_path + '/' + file_name, f.write)
                        print('下载成功')
        else:
            print('忽略列表中的文件不同步')

    @classmethod
    def download(cls, ftp):
        file_list = ftp.nlst()
        print(file_list)
        for i in file_list:
            print(cls.remote_path + "/" + i)
            if i.find('.') != -1:
                print("本地路径", cls.local_path + "\\" + i)
                with open(cls.local_path + "\\" + i, 'wb') as f:
                    ftp.retrbinary('RETR ' + cls.remote_path + "/" + i, f.write)
            else:
                print("目录名称", i)
                if not os.path.exists(cls.local_path + "\\" + i):
                    os.makedirs(cls.local_path + "\\" + i, mode=0o777)
                cls.download_file(ftp, cls.remote_path + "/" + i, cls.local_path + "\\" + i)

    @classmethod
    def download_file(cls, ftp, remote_path, local_path):
        print("ftp文件夹位置", remote_path)
        ftp.cwd(remote_path)
        file_list = ftp.nlst()
        print(file_list)
        for i in file_list:
            print(remote_path + "/" + i)
            if i.find('.') != -1:
                print("本地路径", local_path + "\\" + i)
                with open(local_path + "\\" + i, 'wb') as f:
                    ftp.retrbinary('RETR ' + remote_path + "/" + i, f.write)
            else:
                print("目录名称", i)
                if not os.path.exists(local_path + "\\" + i):
                    os.makedirs(local_path + "\\" + i, mode=0o777)
                cls.download_file(ftp, remote_path + "/" + i, local_path + "\\" + i)

    @classmethod
    def delete_file(cls, ftp, delete_path, file_name):
        ftp.cwd(delete_path)
        try:
            ftp.delete(delete_path + '/' + file_name)
            print('删除成功')
        except Exception as e:
            print('删除失败')